import re
import json
import execjs
import requests
import urllib.parse
from lxml import etree

class ManHua:
    def __init__(self, url):
        self.url = url
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36",
            "Referer": "http://manhua.dmzj.com/"}

    def parse_js(self, r):  # 执行js获取图片链接
        js_str = re.search('eval\((.*?)\)\n', r.text).group(1)
        js_str = js_str.replace('function(p,a,c,k,e,d)', 'function fun(p, a, c, k, e, d)')
        fun = """
                     function run(){
                            var result = %s;
                            return result;
                        }
                """ % js_str
        pages = execjs.compile(fun).call('run')
        data = pages.split('=')[2][1:-2]
        url_list = json.JSONDecoder().decode(data)
        return url_list

    def get_page_list(self):  # 获取列表
        r = requests.get(self.url, headers=self.headers)
        html = etree.HTML(r.text)
        data = html.xpath("//div[@class='cartoon_online_border']/ul//li")
        for li in data:
            page_url = li.xpath("./a/@href")[0]
            page_url = "http://manhua.dmzj.com" + page_url
            page_name = li.xpath("./a/@title")[0]
            return page_url

    def get_page_detail(self, page_url):  # 获取详情页
        r = requests.get(page_url, headers=self.headers)
        imageUrls = self.parse_js(r)
        return (imageUrls, r.url)

    def get_image(self, imageUrls, referer): # 获取并保存图片
        for url in imageUrls:
            imagename = urllib.parse.unquote(url)
            url = "http://images.dmzj.com/" + url
            self.headers["Referer"] = referer
            r = requests.get(url, headers=self.headers)
            with open("-".join(imagename.split("/")[1:]), 'wb') as file:
                file.write(r.content)
            print("%s, 保存成功" % "-".join(imagename.split("/")[1:]))

    def run(self):  # 获取详情
        pageUrl = self.get_page_list()
        imageUrls, referer = self.get_page_detail(pageUrl)
        self.get_image(imageUrls, referer)


if __name__ == '__main__':
    manhua = ManHua("https://manhua.dmzj.com/renyadao/")
    manhua.run()